package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.bean.BeanUtils;
import com.spzx.product.annotation.MyCacheAnnotation;
import com.spzx.product.api.domain.Product;
import com.spzx.product.api.domain.ProductDetails;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.product.api.domain.vo.SkuQuery;
import com.spzx.product.api.domain.vo.SkuStockVo;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.ProductDetailsMapper;
import com.spzx.product.mapper.ProductMapper;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.IProductService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.rmi.server.ServerCloneException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 商品Service业务层处理
 */
@Slf4j
@Service
@Transactional
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductSkuMapper productSkuMapper;

    @Autowired
    private ProductDetailsMapper productDetailsMapper;

    @Autowired
    private SkuStockMapper skuStockMapper;

    //@Autowired
    //private StringRedisTemplate stringRedisTemplate; //适合 key和value都是字符串类型

    @Autowired
    private RedisTemplate redisTemplate; //适合值是任意类型

    /**
     * 查询商品列表
     *
     * @param product 商品
     * @return 商品
     */
    @Override
    public List<Product> selectProductList(Product product) {
        return productMapper.selectProductList(product);
    }

    //原子性
    @Override
    public int insertProduct(Product product) {
        //1.保存Product对象到product表
        productMapper.insert(product); //主键回填

        //2.保存List<ProductSku>对象到product_sku表
        List<ProductSku> productSkuList = product.getProductSkuList();
        if (CollectionUtils.isEmpty(productSkuList)) {
            throw new ServiceException("SKU数据为空");
        }
        int size = productSkuList.size();
        for (int i = 0; i < size; i++) {
            ProductSku productSku = productSkuList.get(i);
            productSku.setSkuCode(product.getId() + "_" + i);
            productSku.setSkuName(product.getName() + " " + productSku.getSkuSpec());
            productSku.setProductId(product.getId());
            productSkuMapper.insert(productSku);

            //添加商品库存  //3.保存List<SkuStock>对象到sku_stock表
            SkuStock skuStock = new SkuStock();
            skuStock.setSkuId(productSku.getId());
            skuStock.setTotalNum(productSku.getStockNum());
            skuStock.setLockNum(0);
            skuStock.setAvailableNum(productSku.getStockNum());
            skuStock.setSaleNum(0);
            skuStockMapper.insert(skuStock);
        }

        //4.保存ProductDetails对象到product_details表
        ProductDetails productDetails = new ProductDetails();
        productDetails.setImageUrls(String.join(",", product.getDetailsImageUrlList()));
        productDetails.setProductId(product.getId());
        productDetailsMapper.insert(productDetails);

        return 1;
    }


    @Override
    public Product selectProductById(Long id) {
        //1.根据id查询Product对象
        Product product = productMapper.selectById(id);

        //2.封装扩展字段：查询商品对应多个List<ProductSku>
        //select * from product_sku where product_id =?
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id));
        List<Long> productSkuIdList = productSkuList.stream().map(productSku -> productSku.getId()).toList();


        // select * from sku_stock where sku_id in (1,2,3,4,5,6)
        List<SkuStock> skuStockList = skuStockMapper.selectList(new LambdaQueryWrapper<SkuStock>().in(SkuStock::getSkuId, productSkuIdList));

        Map<Long, Integer> skuIdToTatalNumMap = skuStockList.stream().collect(Collectors.toMap(SkuStock::getSkuId, SkuStock::getTotalNum));
        productSkuList.forEach(productSku -> {
            //返回ProductSku对象，携带了库存数据；
            productSku.setStockNum(skuIdToTatalNumMap.get(productSku.getId()));
        });

        product.setProductSkuList(productSkuList);

        //3.封装扩展字段：商品详情图片List<String>
        ProductDetails productDetails = productDetailsMapper.selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, id));
        String imageUrls = productDetails.getImageUrls();   //url,url,url
        String[] urls = imageUrls.split(",");
        product.setDetailsImageUrlList(Arrays.asList(urls));
        //返回Product对象
        return product;
    }


    @Override
    public int updateProduct(Product product) {
        //1.更新Product
        productMapper.updateById(product);

        //2.更新SKU   List<ProductSku>
        List<ProductSku> productSkuList = product.getProductSkuList();
        if (CollectionUtils.isEmpty(productSkuList)) {
            throw new ServiceException("SKU数据为空");
        }
        productSkuList.forEach(productSku -> {
            productSkuMapper.updateById(productSku);

            //3.更新库存   List<ProductSku> -> 获取扩展字段stockNum
            SkuStock skuStock = skuStockMapper.selectOne(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, productSku.getId()));
            skuStock.setTotalNum(productSku.getStockNum());
            skuStock.setAvailableNum(skuStock.getTotalNum() - skuStock.getLockNum());
            skuStockMapper.updateById(skuStock);
        });

        //4.更新详情ProductDetails
        ProductDetails productDetails = productDetailsMapper
                .selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, product.getId()));
        productDetails.setImageUrls(String.join(",", product.getDetailsImageUrlList()));
        productDetailsMapper.updateById(productDetails);

        return 1;
    }


    @Override
    public int deleteProductByIds(Long[] ids) {
        //1.删除Product表数据
        // delete from product where id in (1,2)
        productMapper.deleteBatchIds(Arrays.asList(ids));

        //2.删除ProductSku表数据
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().in(ProductSku::getProductId, Arrays.asList(ids)));
        List<Long> productSkuIdList = productSkuList.stream().map(ProductSku::getId).toList();
        productSkuMapper.deleteBatchIds(productSkuIdList);

        //3.删除SkuStock表数据
        skuStockMapper.delete(new LambdaQueryWrapper<SkuStock>().in(SkuStock::getSkuId, productSkuIdList));

        //4.删除ProductDetails表数据
        // delete from product_details where product_id in (1,2)
        productDetailsMapper.delete(new LambdaQueryWrapper<ProductDetails>().in(ProductDetails::getProductId, Arrays.asList(ids)));
        return 1;
    }


    @Override
    public void updateAuditStatus(Long id, Integer auditStatus) {
        Product product = new Product();
        product.setId(id);
        if (auditStatus == 1) {
            product.setAuditStatus(1);
            product.setAuditMessage("审批通过");
        } else {
            product.setAuditStatus(-1);
            product.setAuditMessage("审批拒绝");
        }
        productMapper.updateById(product);
    }

    /**
     * 更新商品状态
     *
     * @param id     商品ID
     * @param status 商品状态，1表示启用，-1表示禁用
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(Long id, Integer status) {
        Product product = new Product();
        product.setId(id);
        // 根据状态值设置商品状态，并在启用时更新Redis中的SKU位图
        if (status == 1) {
            product.setStatus(1);
            String key = "sku:product:data";
            // 查询商品对应的所有SKU信息
            List<ProductSku> productSkuList = productSkuMapper
                    .selectList(new LambdaQueryWrapper<ProductSku>()
                            .eq(ProductSku::getProductId, id));
            // 将每个SKU在Redis位图中对应位置设为true
            productSkuList.forEach(item -> {
                redisTemplate.opsForValue().setBit(key, item.getId(), true);
            });
        } else {
            product.setStatus(-1);
            String key = "sku:product:data";
            // 查询商品对应的所有SKU信息
            List<ProductSku> productSkuList = productSkuMapper
                    .selectList(new LambdaQueryWrapper<ProductSku>()
                            .eq(ProductSku::getProductId, id));
            // 将每个SKU在Redis位图中对应位置设为false
            productSkuList.forEach(item -> {
                redisTemplate.opsForValue().setBit(key, item.getId(), false);
            });
        }
        // 更新商品状态
        productMapper.updateById(product);
    }


    @Override
    public List<ProductSku> getTopSale() {
        return productSkuMapper.getTopSale();
    }


    @Override
    public List<ProductSku> skuList(SkuQuery skuQuery) {
        return productSkuMapper.skuList(skuQuery);
    }


    /**
     * 服务提供者：6个接口来服务于商品详情查询。需要进行优化，提供查询效率。
     * 需要使用redis来提高性能。
     */

    @Override
    public ProductSku getProductSku(Long skuId) {
        try {
            String key = "product:sku:" + skuId;
            ProductSku productSku = null;
            if (redisTemplate.hasKey(key)) {
                productSku = (ProductSku) redisTemplate.opsForValue().get(key);
                log.info("命中缓存，直接返回，线程ID：{}，线程名称：{}", Thread.currentThread().getId(), Thread.currentThread().getName());
                return productSku;
            }
            String lockkey = "product:sku:lock:" + skuId;
            String lockValue = UUID.randomUUID().toString().replace("-", "");
            Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(lockkey, lockValue, 10, TimeUnit.SECONDS);
            if (ifAbsent) {
                log.info("获取锁成功：{}，线程名称：{}", Thread.currentThread().getId(), Thread.currentThread().getName());
                try {
                    productSku = productSkuMapper.selectById(skuId);
                    int timeout = (productSku == null ? 60 : 600) + new Random().nextInt(20);
                    redisTemplate.opsForValue().set(key, productSku, timeout, TimeUnit.SECONDS);
                    return productSku;
                } finally {
                    String scriptText = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                            "then\n" +
                            "    return redis.call(\"del\",KEYS[1])\n" +
                            "else\n" +
                            "    return 0\n" +
                            "end";
                    DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
                    redisScript.setScriptText(scriptText);
                    redisScript.setResultType(Long.class);
                    redisTemplate.execute(redisScript, Arrays.asList(lockkey), lockValue);
                }
            } else {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.error("获取锁失败，自旋：{}，线程名称：{}", Thread.currentThread().getId(), Thread.currentThread().getName());
                return this.getProductSku(skuId);
            }
        } catch (Exception e) {
            //兜底处理方案：Redis服务有问题，将业务数据获取自动从数据库获取
            log.error("[商品服务]查询商品信息异常：{}", e);
            return productSkuMapper.selectById(skuId);
        }
    }


    @Override
    @MyCacheAnnotation(keyPrefix = "product:getProduct", matchValue = "#id")
    public Product getProduct(Long id) {
        return productMapper.selectById(id);
    }


    @Override
    @MyCacheAnnotation(keyPrefix = "product:getSkuPrice", matchValue = "#skuId")
    public SkuPrice getSkuPrice(Long skuId) {
        ProductSku productSku = productSkuMapper.selectOne(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getId, skuId).select(ProductSku::getSalePrice, ProductSku::getMarketPrice));
        SkuPrice skuPrice = new SkuPrice();
        BeanUtils.copyProperties(productSku, skuPrice);
        return skuPrice;
    }


    @Override
    @MyCacheAnnotation(keyPrefix = "product:getProductDetails", matchValue = "#id")
    public ProductDetails getProductDetails(Long id) {
        return productDetailsMapper.selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, id));
    }


    @Override
    @MyCacheAnnotation(keyPrefix = "product:getSkuSpecValue", matchValue = "#id")
    public Map<String, Long> getSkuSpecValue(Long id) {
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id).select(ProductSku::getId, ProductSku::getSkuSpec));
        Map<String, Long> skuSpecValueMap = new HashMap<>();
        productSkuList.forEach(item -> {
            skuSpecValueMap.put(item.getSkuSpec(), item.getId());
        });
        return skuSpecValueMap;
    }


    @Override
    @MyCacheAnnotation(keyPrefix = "product:getSkuStock", matchValue = "#skuId")
    public SkuStockVo getSkuStock(Long skuId) {
        SkuStock skuStock = skuStockMapper.selectOne(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, skuId));
        SkuStockVo skuStockVo = new SkuStockVo();
        BeanUtils.copyProperties(skuStock, skuStockVo);
        return skuStockVo;
    }


    // select * from product_sku where id in (1,2,3)
    // select id,sale_price,market_price from product_sku where id in (1,2,3)
    @Override
    public List<SkuPrice> getSkuPriceList(List<Long> skuIdList) {
        if (CollectionUtils.isEmpty(skuIdList)) {
            return new ArrayList<SkuPrice>();
        }
        List<ProductSku> skuList = productSkuMapper
                .selectList(new LambdaQueryWrapper<ProductSku>().in(ProductSku::getId, skuIdList)
                        .select(ProductSku::getId, ProductSku::getSalePrice, ProductSku::getMarketPrice));
        if (CollectionUtils.isEmpty(skuList)) {
            return new ArrayList<SkuPrice>();
        }
        return skuList.stream().map((sku) -> {
            SkuPrice skuPrice = new SkuPrice();
            skuPrice.setSkuId(sku.getId());
            skuPrice.setSalePrice(sku.getSalePrice());
            skuPrice.setMarketPrice(sku.getMarketPrice());
            return skuPrice;
        }).toList();
    }

    /**
     * 检查并锁定商品库存
     *
     * @param orderNo       订单编号，用于生成Redis锁的key
     * @param skuLockVoList 需要锁定的商品SKU信息列表
     * @return 返回处理结果信息，空字符串表示处理成功，"订单正在处理中"表示订单正在处理，
     * "重复提交"表示重复提交订单
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String checkAndLock(String orderNo, List<SkuLockVo> skuLockVoList) {
        // 生成Redis分布式锁的key，用于防止重复处理同一订单
        String key = "sku:lock:" + orderNo;
        // 生成存储库存检查结果的Redis数据key
        String dataKey = "sku:lock:data:" + orderNo;

        // 使用Redis的SETNX命令（setIfAbsent方法）尝试获取分布式锁
        // 设置锁的过期时间为1小时，防止死锁
        Boolean isExist = redisTemplate.opsForValue().setIfAbsent(key, orderNo, 1, TimeUnit.HOURS);

        // 如果获取锁失败，说明可能有其他线程正在处理该订单
        if (!isExist) {
            // 检查是否还存在锁key，如果存在说明订单正在处理中
            if (redisTemplate.hasKey(key)) {
                return "订单正在处理中";
            } else {
                // 如果锁key不存在，说明是重复提交
                return "重复提交";
            }
        }

        // 遍历需要检查库存的SKU列表
        for (SkuLockVo skuLockVo : skuLockVoList) {
            // 调用skuStockMapper.check方法检查指定SKU是否有足够库存
            // 该方法会检查skuId对应的库存是否大于等于skuNum数量
            SkuStock skuStock = skuStockMapper.check(skuLockVo.getSkuId(), skuLockVo.getSkuNum());

            // 如果返回null，说明库存不足
            if (skuStock == null) {
                skuLockVo.setIsHaveStock(false);  // 设置该SKU库存不足
            } else {
                // 如果返回SkuStock对象，说明库存充足
                skuLockVo.setIsHaveStock(true);   // 设置该SKU库存充足
            }
        }
        // 检查是否存在库存不足的商品
if (skuLockVoList.stream().anyMatch(skuLockVo -> !skuLockVo.getIsHaveStock())) {
    // 初始化结果字符串缓冲区
    StringBuffer result = new StringBuffer();
    // 过滤出库存不足的商品列表
    List<SkuLockVo> noHaveStockSkuLockVoList = skuLockVoList.stream().filter(item -> !item.getIsHaveStock())
            .collect(Collectors.toList());
    // 遍历库存不足的商品，构建错误信息
    for (SkuLockVo skuLockVo : noHaveStockSkuLockVoList) {
        result.append("商品" + skuLockVo.getSkuId() + "库存不足:");
    }
    // 删除Redis中的库存信息
    redisTemplate.delete(key);
    // 返回库存不足的错误信息
    return result.toString();
}

// 遍历商品列表，尝试锁定库存
skuLockVoList.forEach(skuLockVo -> {
    // 调用mapper方法尝试锁定库存
    int row = skuStockMapper.lock(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
    // 如果锁定失败，删除Redis中的库存信息并抛出异常
    if(row==0){
        this.redisTemplate.delete(key);
        throw new ServiceException("锁定库存失败");
    }
});

        // 如果所有商品都锁定成功的情况下，需要缓存锁定信息到redis。以方便将来解锁库存 或者 减库存
        redisTemplate.opsForValue().set(dataKey, skuLockVoList);

        // 返回空字符串表示处理成功
        return "";
    }

    /**
     * 解锁订单库存
     *
     * @param orderNo 订单编号，用于标识需要解锁库存的订单
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void unlock(String orderNo) {
        // 构造Redis锁key和数据key
        String key = "sku:unlock:" + orderNo;
        String dataKey = "sku:lock:data:" + orderNo;

        // 尝试获取分布式锁，防止重复解锁，锁有效期1小时
        Boolean isExist = redisTemplate.opsForValue().setIfAbsent(key, orderNo, 1, TimeUnit.HOURS);
        if (!isExist) return;

        // 获取需要解锁的SKU库存信息列表
        List<SkuLockVo> skuLockVoList = (List<SkuLockVo>) redisTemplate.opsForValue().get(dataKey);
        if (CollectionUtils.isEmpty(skuLockVoList)) return;

        // 遍历SKU列表，逐个解锁库存
        for (SkuLockVo skuLockVo : skuLockVoList) {
            int row = skuStockMapper.unlock(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            if (row == 0) {
                // 解锁失败时删除Redis锁并抛出异常
                this.redisTemplate.delete(key);
                throw new ServiceException("解锁库存失败");
            }
        }

        // 解锁成功后删除Redis中的库存数据
        this.redisTemplate.delete(dataKey);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void minus(String orderNo) {
        String key = "sku:minus:" + orderNo;
        String dataKey = "sku:lock:data:" + orderNo;
        //业务去重，防止重复消费
        Boolean isExist = redisTemplate.opsForValue().setIfAbsent(key, orderNo, 1, TimeUnit.HOURS);
        if (!isExist) return;
        List<SkuLockVo> skuLockVoList = (List<SkuLockVo>) redisTemplate.opsForValue().get(dataKey);
        if (CollectionUtils.isEmpty(skuLockVoList)) return;
        for (SkuLockVo skuLockVo : skuLockVoList) {
            int row = skuStockMapper.minus(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            if (row == 0) {
                this.redisTemplate.delete(key);
                throw new ServiceException("减出库失败");
            }
        }

        this.redisTemplate.delete(dataKey);
    }
}